﻿<?php
/**
 * Chapter Manager Controller
 *
 * Sewiki is a experimental software for course
 * Software Engineering in HIT and it's devoloped
 * upon CodeIgniter Framework. More infomation of
 * the framework, please vist http://codeigniter.com/
 *
 * @package  : CodeIgniter
 * @category : controller/admin
 * @author   : Oneplus <oneplus.lau@gmail.com>
 * @date     : 2011-06-13
 */
class ChapterManager extends CI_Controller {
	/**
	 * The constructor
	 *
	 * @access : public
	 * @return : void
	 */
	function __construct() {
		parent::__construct();
		$this->load->model('graph');
		$this->load->model('chapter');
		$this->load->database();
	}
	
	/**
	 * Method Create Chapter
	 *
	 * Main controller method for admin create chapter
	 * infomation task logic
	 *
	 * @access : public
	 * @param  : int, $bid
	 * @return : void
	 */
	public function createChapter($bid) {
		// step i get max chapter rank in certain book
		$this->db->where(array('bid' => $bid));
		$this->db->select_max('number');
		$chapter = $this->db->get('chapters');
		
		$max_rank = $chapter->row()->number; if(isset($max_rank) == false) $max_rank = 0;
		$num_boxs = 1; // number for dependent box
		$data = array(
			'max_rank' => $max_rank,
			'num_boxs' => $num_boxs);
		
		// step ii load create chapter form
		$this->load->view('admin/CreateChapter', $data);

		// step iii when submit button is pressed check the validity chapter information in form
		// and insert it into database
		if($this->input->post('submit')) {
			$title       = $this->input->post('ctitle');
			$description = $this->input->post('cdesc');
			$number      = $this->input->post('crank');
			$deadline    = $this->input->post('cdead');
			$dep_num     = $this->input->post('cdep_num');
			
			// step iv check whether the deadline is set and it's invalid.
			if($deadline != '') {
				$deadline = strtotime($deadline);
				if($deadline < strtotime("+1 day")) {
					$sessiondata = array('msg' => '章节截止时间设置出错，截止时间过早。');
					$this->session->set_userdata($sessiondata);

					redirect('admin/ChapterManager/createChapter/' . strval($bid));
				}
			}
			
			// step v deadline is valid. or not set
			//  load a virtul dependent graph of the certain book from database
			//  set virtul node in graph with id=100000
			//  make candidate edge set and insert these edges into the graph
			$edges = array();
			$v     = 100000;
			
			for($i = 0; $i < $dep_num; $i ++) {
				$u = $this->input->post('cdep_' . strval($i));
				// means no dependency relation in box_i
				if($u == '0')
					continue;
				// get cid which is index in graph
				// if this chapter is finished, no need to take care of the dep relation.
				$u = $this->chapter->getIdByNumber($u, $bid);
				$chapter = $this->chapter->getChapter($u);
				if($chapter['edit_state'] == 1)
					continue;
				
				// make sure $edges is a set
				if(in_array($u, $edges) == false)
					array_push($edges, array('u' => $u, 'v' => $v));
			}
			
			$this->graph->loadGraph($bid);
			foreach ($edges as $edge) {
				$this->graph->addEdge($edge['u'], $edge['v']);
			}
			$this->graph->displayGraph();
			
			// step vi check whether the graph is topological
			if($this->graph->isTopological() == false) {
				$sessiondata = array('msg' => '章节依赖关系设置出错，出现自依赖现象。');
				$this->session->set_userdata($sessiondata);
				
				redirect('admin/ChapterManager/createChapter/' . strval($bid));
			}
			else {
				// step vii the graph is topological, which means there is not chapter dependent on itself
				//  increase the number of chapters after insert position
				//  insert chapter information into the book
				$this->chapter->increaseNumberByNumber($number, $bid);
				
				$data = array(
					'title' => $title,
					'description' => $description,
					'create_time' => date("Y-m-d H:i:s", time()),
					'bid'         => $bid,
					'number'      => $number + 1);
					
				if(count($edges) == 0) $data['edit_state'] = 0;
				else                   $data['edit_state'] = -1;
				
				if($deadline != '')
					$data['deadline'] = date("Y-m-d", $deadline);
				
				$cid = $this->chapter->createChapter($data);
				
				// step viii instance the virtual graph by insert it into database
				for($i = 0; $i < count($edges); $i ++){
					$edges[$i]['v'] = $cid;
				}
				$this->graph->storeGraph($edges, $bid);

				// step ix show some message
				$sessiondata = array('msg' => '成功创建章节' . $title);
				$this->session->set_userdata($sessiondata);
				redirect('browser/Browser/ChapterList/' . $bid);
			}
		}
	}
}
?>